package com.wxw.BaseLibrary.tool;

/**
 *
 * @author david
 * @date 2014/5/13
 */
public class MathConventor {
    /**
     * 十六进制转二进制
     * @param a
     * @return
     */
    public static String HToB(String a) {
        String b = Integer.toBinaryString(Integer.valueOf(toD(a, 16)));
        return b;
    }

    /**
     * 二进制转十六进制
     * @param a
     * @return
     */
    public static String BToH(String a) {
        // 将二进制转为十进制再从十进制转为十六进制
        String b = Integer.toHexString(Integer.valueOf(toD(a, 2)));
        return b;
    }

    /**
     * 任意进制数转为十进制数
     * @param a
     * @param b
     * @return
     */
    public static String toD(String a, int b) {
        int r = 0;
        for (int i = 0; i < a.length(); i++) {
            r = (int) (r + formatting(a.substring(i, i + 1))
                    * java.lang.Math.pow(b, a.length() - i - 1));
        }
        return String.valueOf(r);
    }

    /**
     * 将十六进制中的字母转为对应的数字
     * @param a
     * @return
     */
    public static int formatting(String a) {
        int i = 0;
        for (int u = 0; u < 10; u++) {
            if (a.equals(String.valueOf(u))) {
                i = u;
            }
        }
        if (Hex_A.equals(a)) {
            i = 10;
        }
        if (Hex_B.equals(a)) {
            i = 11;
        }
        if (Hex_C.equals(a)) {
            i = 12;
        }
        if (Hex_D.equals(a)) {
            i = 13;
        }
        if (Hex_E.equals(a)) {
            i = 14;
        }
        if (Hex_F.equals(a)) {
            i = 15;
        }
        
        return i;
    }


    /**
     * 将十进制中的数字转为十六进制对应的字母
     * @param a
     * @return
     */
    public static String formattingH(int a) {
        String i = String.valueOf(a);
        switch (a) {
            case 10: i = Hex_A;
            break;
            case 11: i = Hex_B;
            break;
            case 12: i = Hex_C;
            break;
            case 13: i = Hex_D;
            break;
            case 14: i = Hex_E;
            break;
            case 15: i = Hex_F;
            break;
        }
        return i;
    }

    public static final String Hex_A = "a";
    public static final String Hex_B = "b";
    public static final String Hex_C = "c";
    public static final String Hex_D = "d";
    public static final String Hex_E = "e";
    public static final String Hex_F = "f";
}